from rest_framework import status
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

from .models import User
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from .serializers import UserCreateSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, \
    AddressTitleSerializer, AddUserBrowsingHistorySerializer
from . import constants
import re
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.decorators import action
from django_redis import get_redis_connection
from goods.models import SKU
from goods.serializers import SKUSerializer
from carts.utils import merge_cart_cookie2redis


class UsernameCountView(APIView):
    # 验证用户名是否存在:只作查询,不涉及序列化器
    def get(self, request, username):
        if not re.search(u'^[\u4e00-\u9fa5a-zA-Z]+', username):
            raise serializers.ValidationError('请至少以一个字母或汉字开头命名!')
        count = User.objects.filter(username=username).count()
        if count > 0:
            raise serializers.ValidationError('用户名已存在')
        return Response({'username': username, 'count': count})


class MobileCountView(APIView):
    # 验证手机号是否存在
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        if count > 0:
            raise serializers.ValidationError('手机号已被注册')
        return Response({'mobile': mobile, 'count': count})


# 登录
class UserJSONWebTokenView(ObtainJSONWebToken):
    # 重写post方法
    def post(self, request, *args, **kwargs):
        # 调用父类的方法实现登录 登录后调用cart.utils.merge_cart_cookie2redis方法 实现购物车的合并
        response = super().post(request, *args, **kwargs)
        if "user_id" not in response.data:
            return response
        # 登录成功后
        user_id = response.data["user_id"]
        response = merge_cart_cookie2redis(request, response, user_id)
        return response


# 注册
class UserRegisterView(CreateAPIView):
    """ 注册分析:
    接收参数:[用户名 密码 确认密码 手机号 短信验证码 是否同意]
    序列化器:是 serializer
    返回:对象 [id username mobile]
    视图类:CreateAPIView"""
    serializer_class = UserCreateSerializer


# 用户中心
class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer
    # jwt验证是否登录,登录后才可以访问视图
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 用户邮箱
class EmailView(UpdateAPIView):
    serializer_class = EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    def get(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        user = User.check_verify_email_token(token)
        if not user:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()
        return Response({'message': 'ok'})


class AddressViewSet(CreateModelMixin, UpdateModelMixin, GenericViewSet):
    serializer_class = UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_delete=False)

    def list(self, request):
        query_set = self.get_queryset()
        serializer = self.get_serializer(query_set, many=True)
        user = request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        })

    def create(self, request, *args, **kwargs):
        count = request.user.addresses.count()
        if count > constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)
        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        address = self.get_object()
        address.is_delete = True
        address.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


class AddUserBrowsingHistoryView(CreateAPIView):
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    # 读取用户浏览记录
    def get(self, request):
        redis_cli = get_redis_connection('history')
        key = 'history_%d' % request.user.id
        history = redis_cli.lrange(key, 0, -1)
        skus = []
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)
        serializer = SKUSerializer(skus, many=True)
        return Response(serializer.data)
